package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 保存套餐信息以及擦菜品信息
     * @param setmealDto
     */
    @Transactional
    @Override
    public void setmealWithDish(SetmealDto setmealDto) {

        //保存基本信息，操作setmeal表
        this.save(setmealDto);
        //保存菜品关系信息，操作setmeal_dish表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //遍历集合，给集合中的setmealDish中id属性赋值
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

    }

    /**
     * 删除套餐信息以及套餐和菜品关联信息
     * @param ids
     */
    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {

        //查询套餐状态是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getStatus,1);
        queryWrapper.in(Setmeal::getId,ids);
        int count = this.count(queryWrapper);

        if (count > 0){
            //不可以删除
            throw new CustomException("套餐正在售卖中,不可以删除");
        }

        //直接删除套餐信息
        this.removeByIds(ids);

        //删除菜品关联信息
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper);

    }

    @Override
    public Page<SetmealDto> pageBySQL(int page,int pageSize, String name) {
        Page<SetmealDto> dtoPage = new Page<>(page,pageSize);
        this.getBaseMapper().pageBySQL(dtoPage,name);
        return dtoPage;
    }


}
